package com.simple.database.test;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

/**
 * java操作MongoDB
 * @author root
 */
public class HelloMongoDB {

	public static void main(String[] args) {
		try {
//			1、连接到MongoDB服务
			MongoClient mc = new MongoClient("127.0.0.1", 27017);

//			2、连接到指定数据库
			MongoDatabase db = mc.getDatabase("demodb");
			
//			3、创建集合
//			db.createCollection("simplelife");
			
//			4、获取集合
			MongoCollection<Document> collection = db.getCollection("users");

//			5、插入文档数据
//			insertCollectionData(collection);
			
//			6、查询文档数据
			findCollectionData(collection);
			
//			7、更新文档数据
//			将文档中likes=100的文档修改为likes=200   
			updateCollectionData(collection);
			
//			8、删除第一个文档数据
			collection.deleteMany(Filters.eq("likes",200));
			collection.deleteOne(Filters.eq("likes",100));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getClass().getName() + "……" + e.getMessage());
		}

	}

	private static void updateCollectionData(
			MongoCollection<Document> collection) {
		Bson filter = Filters.eq("likes", 100);
		Document update = new Document("$set", new Document("likes", 200));
		collection.updateMany(filter, update);
	}

	private static void findCollectionData(MongoCollection<Document> collection) {
		FindIterable<Document> findIterable = collection.find();
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		while(mongoCursor.hasNext()){
			System.out.println(mongoCursor.next());
		}
	}

	/**
	 * 插入文档 1、创建文档org.bson.Document参数为key-value的格式
	 * 2、创建文档集合List<Document>
	 * 3、将文档集合插入数据库集合：mongoCollection.insertMany(List<Document>)
	 * 插入单个文档可以用 ：mongoCollection.insertOne(Document)
	 */
	private static void insertCollectionData(
			MongoCollection<Document> collection) {
		Document document = new Document("title", "MongoDB");
		document.append("description", "database").append("likes", 100)
				.append("by", "Fly");
		List<Document> documents = new ArrayList<>();
		documents.add(document);
		collection.insertMany(documents);
		System.out.println("文档插入成功！");
	}
}
